package com.dh.web.passport;

import com.dh.core.security.EnhanceSecurityUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("passport")
public class PassportController {


    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(@RequestParam String username, @RequestParam String passwd, @RequestParam(value = "to", required = false) String to, RedirectAttributes redirectAttributes) {
        Subject user = SecurityUtils.getSubject();
        UsernamePasswordToken token =
            new UsernamePasswordToken(username, new Sha256Hash(passwd).toHex());
        token.setRememberMe(true);

        try {
            user.login(token);
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("message", "用户名或密码不正确");
            return "redirect:/login";
        }
        return "redirect:/";
    }
    @RequestMapping("/logout")
    public String index(){
        Subject subject = EnhanceSecurityUtils.getSubject();
        subject.logout();
        return "redirect:/";
    }


}
